<template>
  <div>
    <!-- accept 只接受 。xlsx 。xls 文件
         type = file input类型 文件上传 -->
    <input
      ref="excel-upload-input"
      class="excel-upload-input"
      type="file"
      accept=".xlsx, .xls"
      @change="handleClick"
    >
    <!-- drop  松开文件触发
         dragover 在区域拖拽触发
         dragenter 进入拖拽区触发-->
    <div
      class="drop"
      @drop="handleDrop"
      @dragover="handleDragover"
      @dragenter="handleDragover"
    >
      Drop excel file here or
      <el-button
        :loading="loading"
        style="margin-left: 16px"
        size="mini"
        type="primary"
        @click="handleUpload"
      >
        Browse
      </el-button>
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  name: 'UploadExcel',
  props: {
    beforeUpload: Function, // eslint-disable-line
    onSuccess: Function, // eslint-disable-line
  },
  data() {
    return {
      loading: false,
      excelData: {
        header: null,
        results: null
      }
    }
  },
  methods: {
    // 拿到数据 给data数据赋值
    generateData({ header, results }) {
      this.excelData.header = header
      this.excelData.results = results
      this.onSuccess && this.onSuccess(this.excelData)
    },
    handleDrop(e) {
    // 阻止默认行为（阻止浏览器下载excel文件） 阻止冒泡
      e.stopPropagation()
      e.preventDefault()
      // 如果正在上传（button的loading是true） 就不往下执行
      if (this.loading) return
      const files = e.dataTransfer.files
      // 如果不止一个文件
      if (files.length !== 1) {
        // 弹框提示 只支持一个文件
        this.$message.error('Only support uploading one file!')
        return
      }
      const rawFile = files[0] // only use files[0]
      // 如果文件名后缀不是.xlsx, .xls, .csv 提示并不向下执行
      if (!this.isExcel(rawFile)) {
        this.$message.error(
          'Only supports upload .xlsx, .xls, .csv suffix files'
        )
        return false
      }
      // 调用upload方法 上传文件
      this.upload(rawFile)
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
    // 阻止默认行为（阻止浏览器下载excel文件） 阻止冒泡
      e.stopPropagation()
      e.preventDefault()
      //  属性控制在拖放操作中给用户的反馈（通常是视觉上的）。
      //  它会影响在拖拽过程中光标的手势 在新位置生成源项的副本
      e.dataTransfer.dropEffect = 'copy'
    },
    // 点击button按钮时，触发文件上传框
    handleUpload() {
      this.$refs['excel-upload-input'].click()
    },
    // 选择文件时触发 @change
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      //   如果没有选择文件
      if (!rawFile) return
      this.upload(rawFile)
    },
    // 真正的上传逻辑
    upload(rawFile) {
      this.$refs['excel-upload-input'].value = null // fix can't select the same excel
      // beforeUPload =》 父传子传过来的函数 校验
      if (!this.beforeUpload) {
        // 如果没传beforeUpload
        // 默认不需要校验
        // 上传文件
        this.readerData(rawFile)
        return
      }
      // 上传了beforeUpload
      const before = this.beforeUpload(rawFile)
      if (before) {
        // 校验通过
        // 上传文件
        this.readerData(rawFile)
      }
    },
    readerData(rawFile) {
      this.loading = true
      return new Promise((resolve, reject) => {
        // 1.实例化
        const reader = new FileReader()
        // 2.监听函数 读完数据会触发
        reader.onload = (e) => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          // 表头数据
          const header = this.getH··eaderRow(worksheet)
          // 表格数据
          const results = XLSX.utils.sheet_to_json(worksheet)
          // 给data数据赋值
          this.generateData({ header, results })
          this.loading = false
          resolve()
        }
        // 3.读文件
        reader.readAsArrayBuffer(rawFile)
      })
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    isExcel(file) {
      return /\.(xlsx|xls|csv)$/.test(file.name)
    }
  }
}
</script>

<style scoped>
.excel-upload-input {
  display: none;
  z-index: -9999;
}
.drop {
  border: 2px dashed #bbb;
  width: 600px;
  height: 160px;
  line-height: 160px;
  margin: 0 auto;
  font-size: 24px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
}
</style>
